<template>
  <el-dialog v-loading="loading" v-model="dialogVisible" :title="dialogTitle" width="1200" z-index=500>
    <div class="result">
      <el-table :data="tableData" border style="width: 100%" max-height="600">
        <el-table-column type="index" width="50" />
        <el-table-column prop="fileName" label="文件名" show-overflow-tooltip/>
        <el-table-column prop="filePath" label="文件地址" show-overflow-tooltip/>
        <el-table-column prop="type" label="文件类型" :formatter="typeFormatter" min-width="40"/>
        <el-table-column prop="createTime" label="上传时间" />
        <el-table-column prop="size" label="文件大小(MB)" min-width="50"/>
        <el-table-column prop="operator" label="操作" width="280">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="onShowFile(scope.row)"
            >
              预览
            </el-button>
            <el-button
                size="small"
                type="primary"
                @click="onSetIndex(scope.row)"
            >
              设为主页
            </el-button>
            <el-button
                size="small"
                type="primary"
                @click="onDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-form
        ref="formRef"
        :inline="false"
        :model="formData"
        :rules="rules"
        class="demo-form-inline"
    >
      <br />
      <el-row>
        <el-col :span="6">
          <el-form-item label="文件类型">
            <el-select v-model="formData.type">
              <el-option v-for="option in options" :label="option.text" :key="option.text" :value="option.value">
                {{option.text}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文件描述" prop="detail">
            <el-input
                v-model="formData.detail"
                placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="btn_group">
          <el-button type="primary" @click="onUpload">上传</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button @click="onCancel">关闭</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="选择文件" prop="selectedFile">
            <el-upload
                drag
                :http-request="onSelectFile"
                :file-list="fileList"
                list-type="picture-card">
              <div class="el-upload__text">选择文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
  <img-dialog
      v-model:show="imgDialogShow"
      :param="imgEditParam"
      @refresh=""
  ></img-dialog>
  <video-dialog
      v-model:show="vedioDialogShow"
      :param="vedioEditParam"
      @refresh=""
  ></video-dialog>
</template>

<script setup>
import { defineProps, defineEmits, reactive, ref, computed, watch } from "vue";
import {
  uploadFile,
  deleteFile,
  selectFilesByGoodsId, setIndexFile,
} from "@/network/api";
import ImgDialog from "./ImgDialog.vue";
import VideoDialog from "./VideoDialog.vue";

const loading = ref(false);
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  param: {
    type: Object,
    default: null,
  },
});
const tableData = ref([]);
const emits = defineEmits(["update:show", "refresh"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(val) {
    emits("update:show", val);
  },
});

const dialogTitle = computed(() => {
  return "文件管理";
});

watch(dialogVisible, (value) => {
  if (value) {
    resetForm();
  }
  requestData();
});
const formRef = ref();
const rules = reactive({
  selectedFile: [{ required: true, message: "请选择文件", trigger: "blur" }],
  type: [{ required: true, message: "请选择文件类型", trigger: "blur" }],
});

const formData = reactive({
  file: "",
  detail: "",
  type: "图片",
});
const fileList = ref([]);
const resetForm = () => {
  formData.file = "";
  formData.detail = "";
  formData.type = "图片";
  fileList.value = [];
};

const onReset = () => {
  resetForm();
};
const requestData = () => {
  loading.value = true;
  selectFilesByGoodsId({
    goodsId: props.param.id.toString(),
  }).then((res) => {
    if (res?.data) {
    tableData.value = res.data || [];
    } else {
      tableData.value = [];
    }
  }).finally(() => {
    loading.value = false;
  });
};

const onDelete = (row) => {
  deleteFile({
    id: row.id.toString(),
  }).then((res) => {
    if (res?.code === 200) {
      // 删除成功
      ElMessage({
        message: "delete success",
        type: "success",
      });
      requestData();
    } else {
      // 删除失败
      ElMessage({
        message: "delete failed",
        type: "error",
      });
    }
  });
};
const onSetIndex = (row) => {
  setIndexFile({
    fileId: row.id.toString(),
    goodsId: props.param.id.toString(),
  }).then((res) => {
    if (res?.code === 200) {
      // 删除成功
      ElMessage({
        message: "set index success",
        type: "success",
      });
      requestData();
      emits("refresh", true);
    } else {
      // 删除失败
      ElMessage({
        message: "set index failed",
        type: "error",
      });
    }
  });
};
const onCancel = () => {
  emits("update:show", false);
};

const options = [
  {
    value:1,
    text:'图片',
  },
  {
    value:2,
    text:'视频',
  }
]
const onSelectFile = ({file, onProgress, onSuccess, onError}) => {
  formData.file = file;
}
const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return isLt2M;
};
const onUpload = () => {
  uploadFile({
    goodsId: props.param.id.toString(),
    type: formData.type=='图片'?1:formData.type,
    detail: formData.detail,
    file: formData.file,
  }).then((res) => {
    if (res?.code === 200) {
      ElMessage({
        message: "upload success",
        type: "success",
      });
      resetForm();
      requestData();
    } else {
      ElMessage({
        message: "upload failed",
        type: "error",
      });
    }
  });
};

const typeFormatter = (row,column,cellValue) => {
  return cellValue === 1?'图片':'视频';
}

const onShowFile = (row) => {
  if(row.type == 1) {
    onShowImg(row);
  }else if (row.type == 2){
    onShowVedio(row);
  }
}
const vedioDialogShow = ref(false);
const vedioEditParam = ref(null);
const onShowVedio =(row) =>{
  vedioDialogShow.value = true;
  vedioEditParam.value = {
    ...row,
  };
}

const imgDialogShow = ref(false);
const imgEditParam = ref(null);
const onShowImg =(row) =>{
  imgDialogShow.value = true;
  imgEditParam.value = {
    ...row,
  };
}
</script>
<style lang="scss" scoped>
.btn_group {
  text-align: center;
}
</style>
